const plugin = requirePlugin('edu-core')
const emitter = plugin.emitter;
const app = getApp();
const {
  devMode,
  appId
} = require('../../index')
const {
  classTime
} = require('../../config'); 
const {
  buildDayTable,
  sortDayTable
} = require('../../utils/handler');
Page({
  data: {

    items: [],
    currentItem: 0,
    //课程信息
    courseData: [],
    //教务系统课表
    eduCourseData: [],
    //自定义课表
    customCourseData: [],
    classTime: classTime,
    newMsgShow: false,
    eduServe: false,
    //情侣ID
    coupleId:'',
    //自己的ID
    userId:''
  },
  /**
   * 页面路由函数
   */
  tapEvent(e) {
    // this.setData({
    //   navShow:false
    // })
    let Index = e.currentTarget.dataset.index;
    let Key = e.currentTarget.dataset.key;
    // console.log(Index)
    switch (Key) {
      case '考研政治': {
        wx.navigateToMiniProgram({
          appId: 'wx501a84fb75239d2e',
        })
        break
      }
 
      case '空教室': {
        wx.navigateTo({
          url: '/pages/course/empty',
        })
        break
      }
    
      case '课表': {
        let openid = app.globalData.openid;
        wx.navigateTo({
          url: '/pages/edu/timetable/index',
        })
        break
      }
      case '图书检索': {
        /**跳转到图书详情页 */
        wx.navigateTo({
          url: '../booklib/index',
        })
        break
      }
      case '成绩': {
        /**跳转到成绩详情页 */
        wx.navigateTo({
          url: '/pages/score/index',
        })
        break
      }
      case '学校公告': {
        wx.navigateTo({
          url: '../sdust/notice/index',
        })
        break
      }
      case '个人信息': {
        wx.navigateTo({
          url: '/pages/setting/index',
        })
        break
      }
    }
  },
  //就绪页面加载情侣信息
  onReady(){
    wx.cloud.callFunction({
      name:'couples-init',
      success:res=>{
        if(res.result.code == 200){
          this.setData({
            ...res.result.data
          })
        }
      }
    })
  },
  //新建消息
  msgNew(e) {
    if(this.data.isCouple == false){
      wx.showModal({
        title:'提醒',
        content:'是否去绑定情侣关系',
        success:r=>{
          if(r.confirm){
            wx.navigateTo({
              url: '/pages/couples/couples',
            })
          }
        }
      })
    }else{
      this.setData({
        newMsgShow: true
      })
    }
   
  },
  /**
   * @TODO
   * @param {*} e 
   */
  saveMsg(e) {
    let content = e.detail;
    wx.showLoading({
      title: '发送~',
    })
    plugin.publishMsg(this.data.userData.openid,this.data.coupleData.openid,content).then(res=>{
      console.log(res)
      wx.hideLoading({
        success: (res) => {
          wx.showToast({
            title: '发送成功',
            icon:'success'
          })
        },
      })
    })
  },
  /**绑定 */
  toLogin() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
  /**跳转页面 */
  toPage(e) {
    let url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url,
    })
  },
  /**
   * 跳转到其他小程序
   */
  toApplet(e) {
    let appId = e.currentTarget.dataset.appid;
    wx.navigateToMiniProgram({
      appId: appId,
    })
  },
  /**
   * 初始化情侣信息
   */
  initCouples(){
    wx.cloud.callFunction({
      name:'edu-couples-api',
      data:{
        action:'findCouple'
      },
      complete:res=>{
        console.log(res)
        if(res.result.errCode == -1){
          console.log('未绑定情侣')
        }
      }
    })
  },
  onLoad() {
    this.initCouples();
    /**监听 app-reload */
    emitter.on('app-reload', () => {
      //console.log(app.globalData)
      let eduId = app.globalData.eduId;
      if (eduId != null && eduId != undefined && eduId != '') {
        this.setData({
          eduServe: true,
          userId:app.globalData.openid
        })
      }
      // 请求自定义课表
      this.reqCustomTable();
      this.reqTable();
    })
    //this.reqTable();
  },
  onShow() {
    if(this.data.courseData.length == 0){
      this.reqTable();
      this.reqCustomTable();
    }
  },
  //请求自定义课表
  reqCustomTable() {
    plugin.getCustomTable({
      userId: this.data.userId,
      devMode,
      appId,
      weeks: this.data.week
    }).then(res => {
      //console.log(devMode)
      //console.log(res)
      let today = plugin.buildWeeks().todayWeek + 1;
      // console.  log(today)
      let showTable = res.data.filter(function (ele, index) {
        return ele.currentDay == today || ele.currentDay == parseInt(today);
      })
      this.setData({
        customCourseData: showTable
      }, () => {
        this.buildCourseData();
      })
    })
  },
  //构建展示课表
  buildCourseData() {
    let eduCourseData = this.data.eduCourseData;
    let customCourseData = this.data.customCourseData;
    let tarr = eduCourseData.concat(customCourseData);
    tarr = sortDayTable(tarr)
    this.setData({
      courseData: tarr
    })
  },
  /**
   * 请求课表信息
   */
  reqTable() {
    wx.cloud.callFunction({
      name: 'core-table-api',
      data: {
        action: 'getTable',
        params: {}
      },
      success: res => {
        if (res.result.code == 200) {
          if (res.result.data.userInfo != null) {

            let tableData = buildDayTable(res.result.data.tableData || []);

            // console.log(tableData)
            let today = plugin.buildWeeks().todayWeek + 1;
            // console.  log(today)
            let showTable = tableData.filter(function (ele, index) {
              return ele.currentDay == today || ele.currentDay == parseInt(today);
            })

            //console.log(showTable)
            this.setData({
              eduCourseData: showTable
            }, () => {
              this.buildCourseData();
            })
          } else {
            console.warn('用户未绑定教务系统')
          }
        }
      },
      complete: res => {
      //  console.log(res)
        wx.stopPullDownRefresh({
          success: (res) => {},
        })
      }
    })
  },
  onPullDownRefresh() {
    // this.setData({
    //   courseData: []
    // }, () => {
    //   this.reqTable();
    // })

  },
  addItem() {
    this.data.items.push(this.data.currentItem++)
    this.setData({
      items: this.data.items,
      currentItem: this.data.currentItem
    })
  }
})